package com.atguigu.day05;

import com.atguigu.utils.ClickEvent;
import com.atguigu.utils.ClickSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoFlatMapFunction;
import org.apache.flink.util.Collector;

// 查询流
// 一条流是点击流
// 另一条流是：socket流，在socket端口输入要查询的名字，例如Mary，可以将点击流中Mary的点击数据过滤出来
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<ClickEvent> clickStream = env.addSource(new ClickSource());

        DataStreamSource<String> queryStream = env.socketTextStream("localhost", 9999);

        clickStream.keyBy(r -> r.url)
                // 并行度设置为1然后广播，为什么并行度要设置成1？
                .connect(queryStream.setParallelism(1).broadcast())
                .flatMap(new Query())
                .print();

        env.execute();
    }

    public static class Query implements CoFlatMapFunction<ClickEvent, String, ClickEvent> {
        private String queryString = "";

        // 第一条流的数据到达以后触发调用
        @Override
        public void flatMap1(ClickEvent value, Collector<ClickEvent> out) throws Exception {
            if (value.username.equals(queryString)) out.collect(value);
        }

        // 第二条流的数据到达以后触发调用
        @Override
        public void flatMap2(String value, Collector<ClickEvent> out) throws Exception {
            queryString = value;
        }
    }
}
